package controller;

import java.io.IOException;
import java.util.List;

import model.Flight;
import model.FlightIO;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class FlightSearchQuery
 */
public class FlightSearchQuery extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public FlightSearchQuery() {
		super();
		// TODO Auto-generated constructor stub

	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * On a post, the FlightSearchQuery servlet gets the search data from the 
	 * correct parameters. The FlightIO class is then used to search for all 
	 * flights that match the search criteria. Those flights are stored in the
	 * request which is forward to FlightSearchResults.jsp for it to display.
	 * 
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//Get session object
		HttpSession session = request.getSession();

		//Get data from form
		String departure = request.getParameter("departure");
		String destination = request.getParameter("destination");
		String date = request.getParameter("date");
		int seats = Integer.parseInt(request.getParameter("seats"));
		String classType = request.getParameter("class");

		FlightIO flightIO = new FlightIO();
		String classTypeIn;
		
		//Get class type in lower case
		if(classType.equals("Economy")){
			classTypeIn = "economy";
		} else if(classType.equals("Business")){
			classTypeIn = "business";
		} else {
			classTypeIn = "first_class";
		}
		
		//Get flights that match the search criteria
		List<Flight> flights = flightIO.searchFlights(departure, destination, date, classTypeIn, seats);

		//Set various session and request attributes
		session.setAttribute("classType", classType);
		session.setAttribute("seats", seats);
		request.setAttribute("flights", flights);
		request.setAttribute("departure", departure);
		request.setAttribute("destination", destination);
		request.setAttribute("date", date);
		
		//Encode URL
		String url = "/WEB-INF/FlightSearchResults.jsp";		

		//Forward to FlightSearchResults
		RequestDispatcher rd = request.getRequestDispatcher(response.encodeURL(url));
		rd.forward(request, response);
	}
}
